using SqlSugar;
using IM.Easy.Core.Services;
using IM.Easy.Core.Utils;
using IM.Easy.Infrastructure.Query;
using IM.Easy.Core.Extensions;
using IM.Easy.Entity.System;
using IM.Easy.SystemServices.Dtos;
using IM.Easy.SystemServices.IServices;

namespace IM.Easy.SystemServices.Services
{
    public class SysOrgPostService : AppServices<SysOrgPost>, ISysOrgPostService
    {

        public SysOrgPostService(ISqlSugarClient db) : base(db)
        {

        }

        public SysOrgPost Create(SysOrgPost entity)
        {
            //重复校验
            if (Context.Queryable<SysOrgPost>().Any(op => op.OrgId == entity.OrgId && op.PostId == entity.PostId))
            {
                ExceptionUtils.ThrowBusinessException("该组织机构和岗位关系已存在。");
            }
            return Context.Insertable(entity).ExecuteReturnEntity();
        }

        public SysOrgPost GetById(long id)
        {
            // TODO: 添加获取逻辑
            return Context.Queryable<SysOrgPost>().InSingle(id);
        }

        public PageResponse<SysOrgPostDto> GetPageList(SysOrgPostQueryDto query)
        {
            var queryable = Context.Queryable<SysOrgPost>();
            var exp = Expressionable.Create<SysOrgPost, SysPost>();
            exp = exp.AndIF(query.OrgId != default, (op, p) => op.OrgId == query.OrgId)
                     .AndIF(!string.IsNullOrEmpty(query.PostKey), (op, p) => p.Name.Contains(query.PostKey) || p.Code.Contains(query.PostKey))
;
            var page = queryable
                 .InnerJoin<SysPost>((op, p) => op.PostId == p.Id)
                 .Where(exp.ToExpression())
                 .Includes((op) => op.Post)
                 .Includes((op) => op.Org)
                 .ToPageList<SysOrgPost, SysOrgPostDto>(query);
            return page;
        }

        public bool Update(SysOrgPost entity)
        {
            // TODO: 添加更新逻辑
            return Context.Updateable(entity).ExecuteCommandHasChange();
        }

        public bool Delete(params long[] Id)
        {
            // TODO: 添加删除逻辑
            return Context.Deleteable<SysOrgPost>(Id).ExecuteCommandHasChange();
        }

        /// <summary>
        /// 获取组织下可用岗位
        /// </summary>
        /// <param name="orgId"></param>
        /// <returns></returns>
        public List<SysPost> GetPosts(long orgId)
        {
            var posts = Context.Queryable<SysPost>()
                                 .LeftJoin<SysOrgPost>((p, op) => p.Id == op.PostId)
                                 .Where((p, op) => op.OrgId == orgId)
                                 .Where((p, op) => op.IsActive && p.IsActive)
                                 .ToList();
            return posts;
        }
    }
}
